<template>
  <div>
    <div id="container"></div>
    <!-- <div id="myPageTop">
      <el-alert
        title="点击地图任意位置可选择地点"
        type="info"
        :closable="false"
        style="margin-bottom: 10px;"
      />
    </div> -->
    <!-- <div id="myPageTop"> -->
      <!-- <table>
        <tr>
          <td>
            <label>地址信息：</label>
          </td>
        </tr>
        <tr>
          <td>
            <div class="address-info">
              <span>{{ address.province }}</span>
              <span>{{ address.city }}</span>
              <span>{{ address.district }}</span>
              <span>{{ address.detailedAddress }}</span>
            </div>
          </td>
        </tr>
      </table> -->
    <!-- </div> -->
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';

const emit = defineEmits(['update-address']);

const props = defineProps({
  address: {
    type: Object,
    required: true,
    default: () => ({
      province: '',
      city: '',
      district: '',
      detailedAddress: '',
      provinceId: null,
      cityId: null,
      districtId: null
    })
  }
});

const map = ref(null);
const marker = ref(null);
const geocoder = ref(null);

// 添加重置方法
const resetMap = () => {
  if (map.value && marker.value) {
    // 重置到默认位置（北京市中心）
    const defaultPosition = [116.397428, 39.90923];
    map.value.setCenter(defaultPosition);
    marker.value.setPosition(defaultPosition);
    map.value.setZoom(13);
  }
};

// 添加获取经纬度的方法
const getLocation = () => {
  if (marker.value) {
    const position = marker.value.getPosition();
    return {
      longitude: position.getLng(),
      latitude: position.getLat()
    };
  }
  return null;
};

// 暴露方法给父组件
defineExpose({
  resetMap,
  getLocation
});

// 初始化地图
const initMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: '45311cf685d663ffc4d7162fba6335c0'
  }

  const script = document.createElement('script')
  script.src = `https://webapi.amap.com/maps?v=2.0&key=3386e6149a9ef0b34421884b8257f99f&plugin=AMap.PlaceSearch,AMap.Geocoder`
  document.head.appendChild(script)

  script.onload = () => {
    // 创建地图实例
    map.value = new AMap.Map("container", {
      resizeEnable: true,
      zoom: 13,
      center: [116.397428, 39.90923] // 默认北京市中心
    });

    // 创建地理编码实例
    geocoder.value = new AMap.Geocoder({
      city: "全国",
      radius: 500
    });

    // 创建标记点
    marker.value = new AMap.Marker({
      position: [116.397428, 39.90923],
      map: map.value,
      draggable: true, // 可拖动
      cursor: 'move',  // 鼠标悬停点样式
      animation: 'AMAP_ANIMATION_DROP'  // 点标记动画
    });

    // 地图点击事件
    map.value.on('click', handleMapClick);
    
    // 标记点拖动结束事件
    marker.value.on('dragend', handleMarkerDragEnd);

    // 初始化地址位置
    updateMapFromAddress();
  }
};

// 处理地图点击
const handleMapClick = (e) => {
  const lnglat = e.lnglat;
  marker.value.setPosition(lnglat);
  regeoCode(lnglat);
};

// 处理标记点拖动结束
const handleMarkerDragEnd = (e) => {
  const lnglat = marker.value.getPosition();
  regeoCode(lnglat);
};

// 逆地理编码
const regeoCode = (lnglat) => {
  if (geocoder.value) {
    geocoder.value.getAddress(lnglat, (status, result) => {
      if (status === 'complete' && result.regeocode) {
        const addressComponent = result.regeocode.addressComponent;
        
        // 处理直辖市的特殊情况
        let province = addressComponent.province;
        let city = addressComponent.city;
        let district = addressComponent.district;
        
        // 如果是直辖市，城市名称为空，使用省份名称作为城市名称
        if (!city || city.length === 0) {
          if (province === '北京市' || province === '天津市' || 
              province === '上海市' || province === '重庆市') {
            city = province;
          }
        }

        // 检查选择的地址是否在已选择的省市区范围内
        if (props.address.province && props.address.city && props.address.district) {
          // 移除"市"、"省"、"自治区"等后缀进行比较
          const normalizeAddress = (addr) => {
            return addr?.replace(/(省|市|自治区|特别行政区|区|县)$/, '') || '';
          };

          const selectedProvince = normalizeAddress(props.address.province);
          const selectedCity = normalizeAddress(props.address.city);
          const selectedDistrict = normalizeAddress(props.address.district);

          const mapProvince = normalizeAddress(province);
          const mapCity = normalizeAddress(city);
          const mapDistrict = normalizeAddress(district);

          if (selectedProvince !== mapProvince || 
              selectedCity !== mapCity || 
              selectedDistrict !== mapDistrict) {
            ElMessage.error(`选择的位置不在${props.address.province}${props.address.city}${props.address.district}范围内`);
            // 重置标记点到上一个有效位置
            updateMapFromAddress();
            return;
          }
        }
        
        // 确保所有地址组件都有值
        const address = {
          province: province || '',
          city: city || province || '',
          district: district || '',
          detailedAddress: result.regeocode.formattedAddress
            .replace(province || '', '')
            .replace(city || '', '')
            .replace(district || '', '')
            .trim()
        };
        
        console.log('解析到的地址信息:', address);
        
        // 发送地址信息给父组件
        emit('update-address', address);
        
        ElMessage.success('已更新地址信息');
      } else {
        ElMessage.error('地址解析失败');
      }
    });
  }
};

// 根据地址更新地图位置
const updateMapFromAddress = () => {
  if (!map.value || !geocoder.value) return;

  const addressString = `${props.address.province || ''}${props.address.city || ''}${props.address.district || ''}${props.address.detailedAddress || ''}`;
  if (addressString.trim()) {
    geocoder.value.getLocation(addressString, (status, result) => {
      if (status === 'complete' && result.geocodes.length) {
        const location = result.geocodes[0].location;
        map.value.setCenter([location.lng, location.lat]);
        marker.value.setPosition([location.lng, location.lat]);
      }
    });
  }
};

// 监听地址变化
watch(() => props.address, updateMapFromAddress, { deep: true });

onMounted(() => {
  initMap();
});
</script>

<style scoped>
#container {
  width: 100%;
  height: 400px;
}

#myPageTop {
  position: absolute;
  top: 10px;
  left: 10px;
  right: 10px;
  z-index: 100;
}

.address-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.address-info span {
  font-size: 14px;
  color: #333;
}

label {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}
</style>
